﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Net.Sockets;
using _7DaysToDieTools;
using System.ComponentModel;
using System.Windows.Forms;

namespace _7DaysToDieTools.Class
{
    /// <summary>
    /// 网络数据文件下载操作类
    /// </summary>
    public class NetAction
    {
        public ProgressBar proBar;
        public bool Comp = false;
        private WebClient wc;
        /// <summary>
        /// 下载指定URL的文件，并显示进度条
        /// </summary>
        /// <param name="URL">文件URL</param>
        /// <param name="pBar">进度条</param>
        public void DownFile(string URL,ProgressBar pBar)
        {
            DownFile(URL, Sinfo.Data.BasePath + Path.GetFileName(URL), pBar);
        }

        /// <summary>
        /// 下载指定URL的文件
        /// </summary>
        /// <param name="URL">文件URL</param>
        public void DownFile(string URL)
        {
            ProgressBar tmpPBar = new ProgressBar();
            DownFile(URL, tmpPBar);
        }

        /// <summary>
        /// 下载指定URL的文件到指定路径，并显示进度条
        /// </summary>
        /// <param name="URL">文件URL</param>
        /// <param name="LocalPath">本地存放路径</param>
        /// <param name="pBar">进度条</param>
        public void DownFile(string URL,string LocalPath,ProgressBar pBar)
        {
            proBar = pBar;
            wc = new WebClient();
            wc.Proxy = null;
            try
            {
                wc.DownloadFileAsync(new Uri(URL), LocalPath);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_ProgressChange);
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_Component);
            }
            catch (Exception x)
            {
                throw x;
            }
        }

        /// <summary>
        /// 下载指定URL的文件到指定路径
        /// </summary>
        /// <param name="URL">文件URL</param>
        /// <param name="LocalPath">本地存放路径</param>
        public void DownFile(string URL,string LocalPath)
        {
            ProgressBar tmpPBar = new ProgressBar();
            DownFile(URL, LocalPath, tmpPBar);
        }

        private void wc_ProgressChange(object sender,DownloadProgressChangedEventArgs e)
        {
            if (proBar.Value == 100)
            {
                proBar.Value = 0;
            }
            proBar.Value++;
        }

        private void wc_Component(object sender, AsyncCompletedEventArgs e)
        {
            proBar.Value = 100;
            Comp = true;
        }
    }
}
